<script>
import _ from "lodash";
import { h, resolveComponent } from "vue";

export default {
  props: {
    options: Array,
    modelValue: Object,
  },
  data() {
    return {
      data: {},
      pushAction: undefined,
    };
  },
  computed: {
    fields() {
      return Array.isArray(this.options) ? this.options : [];
    },
  },
  watch: {
    modelValue() {
      this.updateValue();
    },
  },
  mounted() {
    this.updateValue();
    this.pushAction = _.debounce(
      () => {
        console.log("pushAction", this.data);
        this.$emit("update:modelValue", this.data);
      },
      200,
      { trailing: true, leading: false }
    );
  },
  methods: {
    updateValue() {
      this.data = this.modelValue;
    },
  },
  render() {
    const buildField = (option) => {
      let value = _.get(this.data, `[${option.id}]`);
      let component = undefined;
      if (option.type === 1) {
        component = resolveComponent("cg-switch");
      } else {
        component = resolveComponent("cg-input-number");
      }

      return h("div", { class: "role-parameter-row" }, [
        h("label", { class: "role-parameter-label" }, [option.name]),
        h("div", { class: "role-parameter-content" }, [
          h(component, {
            modelValue: value,
            ["onUpdate:modelValue"]: (v) => {
              this.data = Object.assign(this.data || {}, { [option.id]: v });
              this.pushAction();
            },
          }),
        ]),
      ]);
    };

    return h("div", { class: "role-parameter" }, this.fields.map(buildField));
  },
};
</script>

<style lang="scss">
.role-parameter {
  font-size: 0.75rem;

  .role-parameter-row {
    margin-bottom: 1rem;
    line-height: 2.25rem;

    .role-parameter-label {
      text-align: right;
      vertical-align: middle;
      float: left;
      color: #333;
      padding: 0 12px 0 0;
      box-sizing: border-box;
      width: 100px;
    }

    .role-parameter-content {
      position: relative;
      margin-left: 100px;

      > * {
        vertical-align: middle;
      }
    }
  }
}
</style>
